package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

public class RegressionCalculator {

    public static BigDecimal[] calculateAB(List<BigDecimal> X, List<BigDecimal> Y) {
        int n = X.size();
        BigDecimal A = BigDecimal.ZERO;
        BigDecimal B = BigDecimal.ZERO;
        BigDecimal C = BigDecimal.ZERO;
        BigDecimal D = BigDecimal.ZERO;
        BigDecimal E = BigDecimal.ZERO;

        // 计算A, B, C, D, E
        for (int i = 0; i < n; i++) {
            BigDecimal xi = X.get(i);
            BigDecimal yi = Y.get(i);
            
            A = A.add(xi.divide(yi, 10, RoundingMode.HALF_UP));
            B = B.add(BigDecimal.ONE.divide(yi.multiply(yi), 10, RoundingMode.HALF_UP));
            C = C.add(BigDecimal.ONE.divide(yi, 10, RoundingMode.HALF_UP));
            D = D.add(xi.divide(yi.multiply(yi), 10, RoundingMode.HALF_UP));
            E = E.add(xi.divide(yi, 10, RoundingMode.HALF_UP).multiply(xi.divide(yi, 10, RoundingMode.HALF_UP)));
        }

        // 计算a和b
        BigDecimal denominator = E.multiply(B).subtract(D.multiply(D));
        BigDecimal a = A.multiply(B).subtract(C.multiply(D)).divide(denominator, 10, RoundingMode.HALF_UP);
        BigDecimal b = E.multiply(C).subtract(D.multiply(A)).divide(denominator, 10, RoundingMode.HALF_UP);

        return new BigDecimal[]{a, b, new BigDecimal(n)};
    }


}
